package com.wandian.cqcsk.mvvm.welcome;

import android.Manifest;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.MainThread;
import androidx.databinding.DataBindingUtil;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.AppOpenBean;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.dialog.VersionUpDialog;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.tools.CSJADTools;
import com.mylib.libcore.tools.GDTADTools;
import com.mylib.libcore.tools.TTAdManagerHolder;
import com.mylib.libcore.utils.ActivityUtil;
import com.mylib.libcore.utils.AppUtil;
import com.mylib.libcore.utils.CityDataUtils;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.ScreenUtils;
import com.mylib.libcore.utils.TabKeyUtils;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;
import com.qq.e.comm.util.AdError;
import com.wandian.cqcsk.R;
import com.wandian.cqcsk.adapter.OpenPagerAdapter;
import com.wandian.cqcsk.databinding.ActivityWelcomeBinding;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import pub.devrel.easypermissions.EasyPermissions;
import yanzhikai.textpath.painter.FireworksPainter;

import static com.mylib.libcore.config.AppConfig.CSJ_OPEN_ID;
import static com.mylib.libcore.config.AppConfig.GDT_APP_OPEN_AD;
import static com.mylib.libcore.config.AppConfig.PERMISSIONS;
import static com.mylib.libcore.config.AppConfig.PERMISSIONSTWO;
import static com.mylib.libcore.config.AppSPKeyConfig.CITY_NAME;
import static com.mylib.libcore.config.AppSPKeyConfig.CITY_STREET_NAME;
import static com.mylib.libcore.config.AppSPKeyConfig.IS_FIRST_OPEN;
import static com.mylib.libcore.config.AppSPKeyConfig.PROVINCE_NAME;

/**
 * 启动页
 * @author
 * @time 2019-12-16 14:00
 */

public class SplashActivity extends BaseMVVMActivity<WelcomeActivityViewModel> implements  EasyPermissions.PermissionCallbacks, AMapLocationListener {
    private final String TAG = "WelcomeActivity";
    private ActivityWelcomeBinding dataBinding;
    private Timer timer = new Timer(); //开屏广告
    private int time = 5;  //设置时间
    private TimerTask task;
    private long mkeyTime =0;//按先home键的时间
    private VersionUpDialog versionUpDialog;//升级弹框
    public AMapLocationClient mlocationClient;//声明mlocationClient对象
    public AMapLocationClientOption mLocationOption;//声明mLocationOption对象
    private static final int REQUEST_PERMISSIONS = 0x6601;
    private ArrayList<View> mList = new ArrayList<>(); //引导页
    private int app_number = 1;//当期版本号
    @Override
    public void init(Bundle savedInstanceState) {
        ActivityUtil.getInstance().toFullWindows(this);  //隐藏顶部的状态栏
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_welcome);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        ActivityUtil.getInstance().showStatusView(this,dataBinding.viewSysTop,true);
        requestPermissions();
        app_number=AppUtil.getPackageVersionCode(this);
        if(UIUtils.isEmpty(app_number))app_number =1;
        initDataView();
        CityDataUtils.getLocalCityJson(this); //初始化城市
    }

    private void initDataView(){
        mViewModel.appOpenBean.observe(this,appOpenBean -> {
            if(!UIUtils.isEmpty(appOpenBean)){
                if(appOpenBean.getAuditV()<=app_number){
                    String tabs = "";
                    if(!UIUtils.isEmpty(appOpenBean.getmStr())){
                        String[] homeTables=appOpenBean.getmStr().split(",");
                        for(String key:homeTables) tabs =tabs + TabKeyUtils.getTabByKey(key);
                    }
                    if(appOpenBean.getAuditV()<app_number){
                        tabs = "天气";
                        AppContext.getInstance().getAppPreferenceForever().setMainTabs("天气");
                    }else  AppContext.getInstance().getAppPreferenceForever().setMainTabs(tabs);

                    String is_first = AppContext.getInstance().getAppPreferenceForever().getKeyValue(IS_FIRST_OPEN);
                    if(!UIUtils.isEmpty(is_first) && is_first.equals("1")){
                        if(!tabs.contains("广告")){//1是开启
                            AppContext.getInstance().getAppPreferenceForever().setADOpen("0");
                            sendCond();
                        }else {
                            AppContext.getInstance().getAppPreferenceForever().setADOpen("1");
                            //加载开屏广告
                            loadSplashAd();
                            //文字绘制
                            dataBinding.llButtom.setVisibility(View.VISIBLE);
                            dataBinding.atpvAs.setPathPainter(new FireworksPainter());
                            dataBinding.atpvAs.startAnimation(0, 1);
                        }
                    }else  initViewPage();
                }
                else showVersionDialog(appOpenBean);
            }
        });
    }

    //倒计时
    private void sendCond() {
        try {
            dataBinding.tvTime.setVisibility(View.VISIBLE);
            dataBinding.tvTime.setOnClickListener(v -> {
                 UIUtils.goToMainActivity();
                if(!UIUtils.isEmpty(task)) task.cancel();
                finish();
            });
            task = new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() { // UI thread
                        @Override
                        public void run() {
                            if (time <= 0) {    //2秒后重新发送
                                 UIUtils.goToMainActivity();
                                if(!UIUtils.isEmpty(task))task.cancel();
                                finish();
                            }else  dataBinding.tvTime.setText(time+" 跳过");
                            time--;
                        }
                    });
                }
            };
            time = 5;
            timer.schedule(task, 0, 1000);
        }catch (Exception e){
        }
    }

    //加载开屏广告
    private void loadSplashAd() {
        Random random = new Random();
        int num = random.nextInt(10);
        if(num<5) CSJADTools.getCSJOpenAD(SplashActivity.this,dataBinding.splashContainer);
        else  GDTADTools.getGDTOpenAD(SplashActivity.this,dataBinding.tvTime,dataBinding.splashContainer);
    }

    private void initViewPage(){
        setPointImg(0);//设置默认图片
        mList.add(View.inflate(this, R.layout.page_item_one, null));
        mList.add(View.inflate(this, R.layout.page_item_two, null));
        mList.add(View.inflate(this, R.layout.page_item_three, null));
        mList.get(mList.size()-1).findViewById(R.id.tv_start).setOnClickListener(v -> {
            AppContext.getInstance().getAppPreferenceForever().setKeyValue(IS_FIRST_OPEN,"1");
            UIUtils.goToMainActivity();
            v.setVisibility(View.GONE);
        });
        dataBinding.viewpager.setAdapter(new OpenPagerAdapter(mList)); //设置适配器
        //监听ViewPager滑动
        dataBinding.viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
            @Override
            public void onPageSelected(int position) {
                setPointImg(position);
            }
            @Override
            public void onPageScrollStateChanged(int state) { }
        });
    }

    //设置小圆点的选中效果
    private void setPointImg(int chooseIndex) {
        dataBinding.point1.setBackgroundResource(R.drawable.button_white_circle_ball);
        dataBinding.point2.setBackgroundResource(R.drawable.button_white_circle_ball);
        dataBinding.point3.setBackgroundResource(R.drawable.button_white_circle_ball);
        switch (chooseIndex){
            case 0:
                dataBinding.point1.setBackgroundResource(R.drawable.button_yellow_circle_ball);
                break;
            case 1:
                dataBinding.point2.setBackgroundResource(R.drawable.button_yellow_circle_ball);
                break;
            case 2:
                dataBinding.point3.setBackgroundResource(R.drawable.button_yellow_circle_ball);
                break;
        }
    }

    //获取当前坐标
    private void getLocation(){
        mlocationClient = new AMapLocationClient(SplashActivity.this);
        mLocationOption = new AMapLocationClientOption(); //初始化定位参数
        if(!UIUtils.isEmpty(mlocationClient) && !UIUtils.isEmpty(mLocationOption)){
            mlocationClient.setLocationListener(this); //设置定位监听
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setInterval(30*60*1000);//设置定位间隔,单位毫秒,默认为2000ms
            mlocationClient.setLocationOption(mLocationOption);//设置定位参数
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            //启动定位
            mlocationClient.startLocation();
        }
    }

    //申请权限
    private void requestPermissions() {
        if (!EasyPermissions.hasPermissions(this, PERMISSIONS)) {
            EasyPermissions.requestPermissions(this, "为保证APP正常使用，请允许文件存储等权限", REQUEST_PERMISSIONS, PERMISSIONS);
        }else {
            getLocation(); //获取坐标
            mViewModel.getVersion(app_number);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 将结果转发到EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if(UIUtils.checkPermissionAllGranted(this,PERMISSIONSTWO)){
            getLocation();  //获取坐标
            mViewModel.getVersion(app_number);
        }else {
            requestPermissions();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {}

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mkeyTime) > 1500) {
                mkeyTime = System.currentTimeMillis();
                ToastUtil.show("再按一次退出登录");
            } else  System.exit(0);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null && !UIUtils.isEmpty(mlocationClient)) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                //设置经纬度
                AppContext.getInstance().getAppPreferencesHelper().setLocation(amapLocation.getLatitude()+"",amapLocation.getLongitude()+"");
                AppContext.getInstance().getAppPreferencesHelper().setKeyValue(PROVINCE_NAME,amapLocation.getProvince()+"");
                AppContext.getInstance().getAppPreferencesHelper().setKeyValue(CITY_NAME,amapLocation.getCity()+"");
                AppContext.getInstance().getAppPreferencesHelper().setKeyValue(CITY_STREET_NAME,amapLocation.getDistrict()+ amapLocation.getStreet()+"");
            } else Log.d(TAG,"location-ErrCode:" + amapLocation.getErrorCode() + ", errInfo:" + amapLocation.getErrorInfo());
        }
    }

    //展示弹框
    private void showVersionDialog(AppOpenBean appOpenBean){
        try {
            versionUpDialog = new VersionUpDialog(getContext(),appOpenBean,null);
            if(!UIUtils.isEmpty(dataBinding.llWelcome))  versionUpDialog.showAtLocation(dataBinding.llWelcome, Gravity.CENTER, 0, 0);
        } catch (Exception e) { e.printStackTrace(); }
    }

    @Override
    protected void onDestroy() {
        try {
            if(!UIUtils.isEmpty(task)){
                task.cancel();
                task = null;
            }
            if(!UIUtils.isEmpty(timer)){
                timer.cancel();
                timer = null;
            }
            if(!UIUtils.isEmpty(mlocationClient)){
                mlocationClient.onDestroy();
            }
        }catch (Exception e){
        }
        super.onDestroy();
    }
}
